package com.iknight.mgr.controller;

import com.github.pagehelper.PageInfo;
import com.iknight.mgr.api.OrgService;
import com.iknight.mgr.core.base.BaseController;
import com.iknight.mgr.core.constant.IkgConstantCode;
import com.iknight.mgr.core.jstree.JsTreeNode;
import com.iknight.mgr.core.jstree.NodeStatus;
import com.iknight.mgr.core.utils.IkgStringUtils;
import com.iknight.mgr.core.utils.IkgWebUtils;
import com.iknight.mgr.model.OrgModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by jeryzym on 2017/7/27.
 */
@RestController
@RequestMapping("/rest/org")
public class OrgController implements BaseController<OrgModel> {

    private static Logger logger = LogManager.getLogger(OrgController.class);

    @Autowired
    private OrgService orgService;

    @Value("${enableRoot}")
    private boolean enableRoot;
    @Value("${rootName}")
    private String rootName;

    public OrgModel format(Map<String, Object> params) {
        OrgModel record = new OrgModel();
        record.setOrg_id(IkgStringUtils.ObjectToString(params.get("org_id")));
        if (IkgStringUtils.isNotNull(params.get("org_code"))) {
            record.setOrg_code(IkgStringUtils.ObjectToString(params.get("org_code")));
        }
        if (IkgStringUtils.isNotNull(params.get("org_name"))) {
            record.setOrg_name(IkgStringUtils.ObjectToString(params.get("org_name")));
        }

        if (IkgStringUtils.isNotNull(params.get("org_level"))) {
            record.setOrg_level(IkgStringUtils.ObjectToString(params.get("org_level")));
        }
        if (IkgStringUtils.isNotNull(params.get("org_type"))) {
            record.setOrg_type(IkgStringUtils.ObjectToString(params.get("org_type")));
        }
        if (IkgStringUtils.isNotNull(params.get("p_org_id"))) {
            record.setP_org_id(IkgStringUtils.ObjectToString(params.get("p_org_id")));
        }
        if (IkgStringUtils.isNotNull(params.get("record_status"))) {
            record.setRecord_status(IkgStringUtils.ObjectToInt(params.get("record_status")));
        }
        if (IkgStringUtils.isNotNull(params.get("expire_date"))) {
            record.setExpire_date(IkgStringUtils.ObjectToString(params.get("expire_date")));
        }
        if (IkgStringUtils.isNotNull(params.get("edit_status")) && IkgStringUtils.ObjectToString(params.get("edit_status")).equals("0")) {
            record.setEffective_date(IkgStringUtils.getCurrentDate("yyyy-MM-dd HH:mm"));
        }

        return record;
    }


    @PostMapping("/save")
    public Object save(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        if (isPKeyNotNull(params)) {
            OrgModel record = format(params);
            orgService.save(record);
            return IkgWebUtils.postIkgResponse(true, "保存成功!", IkgConstantCode.OPERSUCCESS);
        } else {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
    }

    /**
     *
     * @param params
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        if (isPKeyNotNull(params)) {
            String orgId = IkgStringUtils.ObjectToString(params.get("org_id"));
            //判断是否有子节点，如果有子节点，则不进行删除，避免级联删除时误删
            List children = orgService.getTreeNode(orgId);
            if (null != children && children.size() > 0) {
                return IkgWebUtils.postIkgResponse(false, "检测到该组织机构下存在子节点，请先将子节点进行删除", IkgConstantCode.OPERFAILURE);
            }
            orgService.delete(orgId);
            return IkgWebUtils.postIkgResponse(true, "删除成功!", IkgConstantCode.OPERSUCCESS);
        } else {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
    }

    @PostMapping("/selectOne")
    public Object selectOne(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        if (null != params) {
            String orgId = IkgStringUtils.ObjectToString(params.get("org_id"));
            OrgModel record = (OrgModel) orgService.selectOne(orgId);
            return IkgWebUtils.postIkgResponse(true, "查询成功!", record);
        } else {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
    }

    @PostMapping("/selectByCond")
    public Object selectByCond(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        if (null != params) {

        } else {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
        return null;
    }

    @PostMapping("/list")
    public Object selectByPage(@RequestBody Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        if (null != params) {
            int pageIndex = IkgStringUtils.ObjectToInt(params.get("pageNumber"));
            int pageSize = IkgStringUtils.ObjectToInt(params.get("pageSize"));

            PageInfo<OrgModel> result = orgService.selectPage(params, pageIndex, pageSize);
            return IkgWebUtils.postResult(result.getTotal(), result.getList());
        } else {
            return IkgWebUtils.postIkgResponse(false, "传入参数为空", IkgConstantCode.PARAMSNULL);
        }
    }

    @PostMapping("/getTreeNodes")
    public Object lazyLoadTree(@RequestBody Map<String, Object> params, HttpServletRequest request,
                               HttpServletResponse response) {
        String nodeId = IkgStringUtils.ObjectToString(params.get("nodeId"));
        if (nodeId.equals("#")) {
            nodeId = "";
        }
        JsTreeNode rootNode = new JsTreeNode();
        List<OrgModel> result = (List<OrgModel>) orgService.getTreeNode(nodeId);
        List<JsTreeNode> treeNodes = new ArrayList<>();

        if (enableRoot) {//自定义根节点
            rootNode.setId(UUID.randomUUID().toString());
            rootNode.setText(rootName);

            rootNode.setParent("#");
            rootNode.setState(new NodeStatus(false, false, false, false));
            JSONObject rootAttr = new JSONObject();
            rootAttr.put("isRoot", true);
            rootNode.setAttributes(rootAttr);
            rootNode.setChildren(new ArrayList());
            rootNode.setIcon("fa fa-bank");
            treeNodes.add(rootNode);
        }

        Iterator<OrgModel> ita = result.iterator();
        while (ita.hasNext()) {
            OrgModel record = ita.next();

            JsTreeNode jsTreeNode = new JsTreeNode();
            jsTreeNode.setId(record.getOrg_id());
            jsTreeNode.setText(record.getOrg_name());

            JSONObject attr = new JSONObject();
            attr.put("org_code", record.getOrg_code());
            attr.put("org_level", record.getOrg_level());
            attr.put("org_type", record.getOrg_type());
            jsTreeNode.setAttributes(attr);
            jsTreeNode.setState(new NodeStatus(false, false, false, false));
            jsTreeNode.setChildren(new ArrayList());
            jsTreeNode.setIcon("fa fa-bank");

            if (IkgStringUtils.ObjectToString(record.getP_org_id()).length() == 0 || IkgStringUtils.ObjectToString(record.getP_org_id()).equals(nodeId)) {
                if (enableRoot) {
                    jsTreeNode.setParent(rootNode.getId());
                } else {
                    jsTreeNode.setParent("#");
                }
            } else {
                jsTreeNode.setParent(record.getP_org_id());
            }

            treeNodes.add(jsTreeNode);
        }

        return JSONArray.fromObject(treeNodes);
    }

    @PostMapping("/loadOrgTreeNodes")
    public Object getOrgTreeNodes(HttpServletRequest request, HttpServletResponse response) {
        JsTreeNode rootNode = new JsTreeNode();
        List<OrgModel> result = (List<OrgModel>) orgService.selectAll();
        List<JsTreeNode> treeNodes = new ArrayList<>();

        if (enableRoot) {//自定义根节点
            rootNode.setId(UUID.randomUUID().toString());
            rootNode.setText(rootName);

            rootNode.setParent("#");
            rootNode.setState(new NodeStatus(false, false, false, false));
            JSONObject rootAttr = new JSONObject();
            rootAttr.put("isRoot", true);
            rootNode.setAttributes(rootAttr);
            rootNode.setChildren(new ArrayList());
            rootNode.setIcon("fa fa-bank");
            treeNodes.add(rootNode);
        }

        Iterator<OrgModel> ita = result.iterator();
        while (ita.hasNext()) {
            OrgModel record = ita.next();

            JsTreeNode jsTreeNode = new JsTreeNode();
            jsTreeNode.setId(record.getOrg_id());
            jsTreeNode.setText(record.getOrg_name());

            JSONObject attr = new JSONObject();
            attr.put("org_code", record.getOrg_code());
            attr.put("org_level", record.getOrg_level());
            attr.put("org_type", record.getOrg_type());
            jsTreeNode.setAttributes(attr);
            jsTreeNode.setState(new NodeStatus(false, false, false, false));
            jsTreeNode.setChildren(new ArrayList());
            jsTreeNode.setIcon("fa fa-bank");

            if (IkgStringUtils.ObjectToString(record.getP_org_id()).length() == 0) {
                if (enableRoot) {
                    jsTreeNode.setParent(rootNode.getId());
                } else {
                    jsTreeNode.setParent("#");
                }
            } else {
                jsTreeNode.setParent(record.getP_org_id());
            }

            treeNodes.add(jsTreeNode);
        }

        return JSONArray.fromObject(treeNodes);
    }

    public boolean isPKeyNotNull(Map<String, Object> params) {
        return params != null && params.get("org_id") != null;
    }
}
